package com.house.service.impl;

import com.house.dto.UserDTO;
import com.house.entity.User;
import com.house.reportisy.UserRepository;
import com.house.service.UserSerivce;
import com.house.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

import static com.house.utils.Constant.*;

/**
 * @version 1.0
 * @Author OhygC
 * @since 1.0
 */
@Service("UserSerivce")
public class UserServiceImpl implements UserSerivce {


    @Resource
    private UserRepository userRepository;


    @Override
    public int updateUser(User user) {
        //获取当前用户id，用户名
        Integer id = user.getId();
        String username = user.getUsername();
        //获取盐
        String salt = userRepository.getSaltById(id);
        //加盐加密
        String s = salt+user.getPassword();
        String password = DigestUtils.md5DigestAsHex(s.getBytes());
        return userRepository.updateUsername(username,password,id);
    }


    @Override
    public User register(UserDTO userDTO) {
        //创建一个新对象
        User user = new User();
        //将传入对象的所有值赋值给新对象，id除外
        BeanUtils.copyProperties(userDTO,user,"id");
        //制盐
        String salt = DigestUtils.md5DigestAsHex(UUID.randomUUID().toString().getBytes());
        user.setSalt(salt);
        //加盐加密
        String s = salt+userDTO.getPassword();
        String password = DigestUtils.md5DigestAsHex(s.getBytes());
        user.setPassword(password);
        //新增对象
        return userRepository.save(user);
    }

    @Override
    public User selectUserByPhone(String phone) {
        return userRepository.getUserByPhone(phone);
    }

    @Override
    public User login(UserDTO userDTO) {
        User user = new User();
        //用户输入的手机号
        String phone = userDTO.getPhone();

        //获取该手机号的盐
        User salt = userRepository.getSaltByPhone(phone);
        String salt1 = salt.getSalt();
        //通过原有的盐和密码进行加密
        String s = salt1+userDTO.getPassword();
        String password = DigestUtils.md5DigestAsHex(s.getBytes());

        user.setPassword(password);
        return user;
    }

    @Override
    public int findUsersTotal(String string) {
        //如果参数是1，也就代表进来的是状态码
        if (string.equals("1")){
            //查询待审核的所有用户数量
            return userRepository.countUserByStateEquals(DEFUALT_VALUE);
        }
        //如果参数是USER_ROLE，也就代表进来的是普通用户
        if (string.equals(USER_ROLE)){
            //查询所有普通用户数量
            return userRepository.countUserByDelFlagAndUserRoleEquals(DEL_FLAG, USER_ROLE);
        }
        //查询所有房东用户数量
        return userRepository.countUserByDelFlagAndUserRoleEquals(DEL_FLAG, USER_ROLE1);
    }

    @Override
    public Page<Map<String, Object>> findUsers(Map<String, Object> params) {
        Integer page = (Integer) params.get("page") - 1;
        Integer size = (Integer) params.get("size");
        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //分页
        Pageable pageable = PageRequest.of(page, size, sort);
        //如果为普通用户
        if (params.get("userRole").equals(USER_ROLE)){
            //执行查询普通用户的自定义SQL
            Page<Map<String, Object>> list = userRepository.nativeQueryPagingList(pageable);
            return list;
        }
        //执行查询房东的自定义SQL
        Page<Map<String, Object>> list =  userRepository.nativeQueryPagingList1(pageable);
        return list;
    }

    @Override
    public User findUserById(Integer id) {
        return userRepository.getReferenceById(id);
    }

    @Override
    public int updateState(Integer id) {
        return userRepository.updateStateById(id);
    }

    @Override
    public int updateState1(Map<String, Integer> params) {
        Integer id = params.get("id");
        return userRepository.updateState1ById(id);
    }

    @Override
    public Page<Map<String, Object>> findUsersByState(Map<String, Object> params) {
        Integer page = (Integer) params.get("page")-1;
        Integer size = (Integer) params.get("size");
        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //分页
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<Map<String, Object>> list =  userRepository.nativeQueryPagingList2(pageable);
        return list;
    }

    @Override
    public Page<User> findUsersByName(UserDTO userDTO) {
        Integer page = userDTO.getPage() - 1;
        Integer size = userDTO.getSize();
        //排序
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        //分页
        Pageable pageable = PageRequest.of(page, size, sort);
        //使用Specification进行条件查询
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = predicate.getExpressions();
                expressions.add(criteriaBuilder.like(root.get("uname"),"%"+userDTO.getUname()+"%"));
                expressions.add(criteriaBuilder.equal(root.get("userRole"),userDTO.getUserRole()));
                return predicate;
            }
        };
        return userRepository.findAll(specification,pageable);
    }

    @Override
    public Optional<User> findOneUserById(Integer id) {
        return userRepository.findById(id);
    }
}
